package nongchang.kuaijiecaifu.com.ncapp_android.ui.widget;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

public abstract class OnLoadeMoreListener extends RecyclerView.OnScrollListener {

    private int previousTotal = 0; // The total number of items in the dataset after the last load
    private boolean loading = true; // True if we are still waiting for the last set of home to load.
    private int visibleThreshold = 5; // The minimum amount of items to have below your current scroll position before loading more.


    private int currentPage = 1;

    public boolean enable = true;


    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        if (!enable) {
            return;
        }

        LinearLayoutManager llm = (LinearLayoutManager)recyclerView.getLayoutManager();


        int visibleItemCount = recyclerView.getChildCount();
        int totalItemCount = llm.getItemCount();
        int firstVisibleItem = llm.findFirstVisibleItemPosition();

        if (loading) {
            if (totalItemCount > previousTotal) {
                loading = false;
                previousTotal = totalItemCount;
            }
        }
        if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
            currentPage++;

            onLoadMore(currentPage);

            loading = true;
        }

    }

    public abstract void onLoadMore(int page);
}